package com.atao.baokede.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.domain.Article;
import com.atao.baokede.mapper.*;
import com.atao.baokede.pojo.*;
import com.atao.baokede.pojo.vo.ChargeOrderVo;
import com.atao.baokede.pojo.vo.ChargeOrderVo2;
import com.atao.baokede.service.AdminService;
import com.atao.baokede.service.CartService;
import com.atao.baokede.service.ItemService;
import com.atao.baokede.service.MerchantMessageService;
import com.atao.baokede.utils.ThreadLocalUtil;
import com.atao.baokede.websocket.MessageServer;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.atao.baokede.constant.ItemConstant.*;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private MessageServer messageServer;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CartMapper cartMapper;

    @Override
    public void agreeItem(Long itemId) throws IOException {
        // 修改商品状态
        adminMapper.agreeItem(itemId, STATUS_ON_SALE);

        // 获取商品信息
        Item item = itemMapper.findById(itemId);
        // 先判断商品是否在Elasticsearch中，如果在则先删除
        GetRequest request3 = new GetRequest();
        request3.index("items").id(item.getId().toString());
        GetResponse response = client.get(request3, RequestOptions.DEFAULT);
        if (response.getSourceAsString()!=null){
            DeleteRequest request2 = new DeleteRequest();
            request2.index("items").id(item.getId().toString());
            client.delete(request2, RequestOptions.DEFAULT);
        }
        // 将商品信息添加到Elasticsearch中
        ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);
        IndexRequest request = new IndexRequest("item").id(itemDoc.getId());
        request.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
        //检查商品分类是否存在，不存在的话加到分类表中
        if (item.getIsUserAddCategory() == 1) {
            categoryMapper.addCategory(item.getCategory());
        }
    }

    @Override
    public void refuseItem(Long itemId, String reason) throws IOException {
        // 修改商品状态
        adminMapper.refuseItem(itemId, STATUS_AUDIT_FAILED);
        Item item = itemMapper.findById(itemId);
        MerchantMessage message = new MerchantMessage();
        message.setTitle("商品审核失败");
        message.setContent(reason);
        message.setData(JSONUtil.toJsonStr(item));
        message.setMerchantId(item.getMerchantId());
        messageMapper.addMessage(message);
        messageServer.sendToMerchant(item.getMerchantId().toString(), message);
        cartService.disableCartItem(itemId);
        // 检查ElasticSearch中存不存在该商品，如果存在则删除
        GetRequest request3 = new GetRequest();
        request3.index("items").id(item.getId().toString());
        GetResponse response = client.get(request3, RequestOptions.DEFAULT);
        if (response.getSourceAsString()!=null){
            DeleteRequest request2 = new DeleteRequest();
            request2.index("items").id(item.getId().toString());
            client.delete(request2, RequestOptions.DEFAULT);
        }
    }

    @Override
    public void disableUser(Long userId) {
        adminMapper.disableUser(userId);
    }

    @Override
    public void disableMerchant(Long merchantId) throws IOException {
        itemService.disableItemsByMerchantId(merchantId);
        adminMapper.disableMerchant(merchantId);
        // 删除该商户Elasticsearch中所有的商品
        List<Long> itemIds =itemService.findItemsIdByMerchantId(merchantId);

        if (itemIds == null || itemIds.isEmpty()) {
            // 如果没有商品需要删除，直接返回
            return;
        }

        BulkRequest request = new BulkRequest();

        for (Long itemId : itemIds){
            request.add(new DeleteRequest().index("items").id(itemId.toString()));
        }

        client.bulk(request, RequestOptions.DEFAULT);
    }

    @Override
    public void enableUser(Long userId) {
        adminMapper.enableUser(userId);
    }

    @Override
    public void enableMerchant(Long merchantId) {
        itemService.enableItemsByMerchantId(merchantId);
        adminMapper.enableMerchant(merchantId);
    }

    @Override
    public PageBean<User> findUserByName(String keyword, Integer pageNum, Integer pageSize) {
        PageBean<User> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = adminMapper.findUserByName(keyword);
        Page<User> p = (Page<User>) users;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public PageBean<Merchant> findMerchantByName(String keyword, Integer pageNum, Integer pageSize) {
        PageBean<Merchant> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<Merchant> merchants = adminMapper.findMerchantByName(keyword);
        Page<Merchant> p = (Page<Merchant>) merchants;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }


    @Override
    public PageBean<ChargeOrderVo> findUserBalancePayOrdersByKeyword(Integer pageNum, Integer pageSize,Integer orderStatus, String userKeyword, String orderNoKeyword) {
        //1、创建PageBean对象
        PageBean<ChargeOrderVo> pb = new PageBean<>();

        // 根据userKeyword在user表中查询用户ID集合
        List<Long> userIds = null;
        if (userKeyword != null && !userKeyword.trim().isEmpty()) {
            PageHelper.clearPage(); // 避免分页影响
            userIds = userMapper.findUsersByUserKeyword(userKeyword);
            // 如果用户搜索关键词没有匹配到任何用户，且同时提供了订单号搜索条件，则直接返回空结果
            if ((userIds == null || userIds.isEmpty()) && orderNoKeyword != null && !orderNoKeyword.trim().isEmpty()) {
                pb.setTotal(0L);
                pb.setItems(new ArrayList<>());
                return pb;
            }
        }

        //2、开启分页查询,调用PageHelper插件
        PageHelper.startPage(pageNum, pageSize);

        //3、根据userIds和orderNoKeyword在charge_order表中查询数据
        List<ChargeOrder> chargeOrders = adminMapper.findUserBalancePayOrdersByKeyword(orderStatus,userIds, orderNoKeyword);

        List<ChargeOrderVo> chargeOrderVos = BeanUtil.copyToList(chargeOrders, ChargeOrderVo.class);

        // 填充chargeOrderVos中字段username - 使用批量查询优化
        if (!chargeOrderVos.isEmpty() && userIds != null && !userIds.isEmpty()) {
            // 批量查询用户信息
            List<User> users = adminMapper.findUsersByIds(userIds);
            Map<Long, String> userIdToNameMap = users.stream()
                    .collect(Collectors.toMap(User::getId, User::getUsername));

            // 给ChargeOrderVos中的username字段设置用户名（与id对应）
            for (int i = 0; i < chargeOrderVos.size(); i++) {
                ChargeOrderVo vo = chargeOrderVos.get(i);
                ChargeOrder originalOrder = chargeOrders.get(i);
                vo.setUsername(userIdToNameMap.get(originalOrder.getUserId()));
            }
        } else if (!chargeOrderVos.isEmpty()) {
            // 如果没有用户ID列表，但仍需要填充用户名
            // 提取订单中的所有用户ID
            List<Long> orderUserIds = chargeOrders.stream()
                    .map(ChargeOrder::getUserId)
                    .distinct()
                    .collect(Collectors.toList());

            if (!orderUserIds.isEmpty()) {
                List<User> users = adminMapper.findUsersByIds(orderUserIds);
                Map<Long, String> userIdToNameMap = users.stream()
                        .collect(Collectors.toMap(User::getId, User::getUsername));

                // 填充用户名
                for (int i = 0; i < chargeOrderVos.size(); i++) {
                    ChargeOrderVo vo = chargeOrderVos.get(i);
                    ChargeOrder originalOrder = chargeOrders.get(i);
                    vo.setUsername(userIdToNameMap.get(originalOrder.getUserId()));
                }
            }
        }

        //把数据填充到PageBean对象中
        // 确保正确获取分页信息
        if (chargeOrders instanceof Page) {
            Page<ChargeOrder> p = (Page<ChargeOrder>) chargeOrders;
            pb.setTotal(p.getTotal());
            pb.setItems(chargeOrderVos);
        } else {
            // 如果分页信息丢失，手动设置
            pb.setTotal(((Number)(chargeOrders.size())).longValue());
            pb.setItems(chargeOrderVos);
        }

        return pb;
    }

    @Override
    public PageBean<Item> findItemsByStateAndInformation(Integer state, String itemKeyword, String itemCategory, String itemBrand, Integer pageNum, Integer pageSize) {
        PageBean<Item> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<Item> items = adminMapper.findItemsByStateAndInformation(state, itemKeyword, itemCategory, itemBrand);
        Page<Item> p = (Page<Item>) items;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }


}
